﻿using JinfuyuanProject.Entity;
using JinfuyuanProject.Service;
using JinfuyuanProject.Service.Interface;
using System;


using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace JinfuyuanProject.Controllers
{
    public class MailboxController : Controller
    {
        private readonly IMessageInfoService _messageInfoService;

        // GET: Mailbox
        public MailboxController(IMessageInfoService messageInfoService) 
        {
            _messageInfoService=messageInfoService;
        }
        #region 页面
        //聊天窗
        public ActionResult Mailbox()
        {
            var currentUser = HttpContext.Session["user"] as Staff;
            ViewBag.account=currentUser.Name;
            return View();
        }
        #endregion

        #region 接口
        //用来显示得到数据库中邮件的接口
        [HttpPost] 
        public JsonResult Mail(String SearchWord)
        {
            Staff staff = Session["user"] as Staff;
            Hashtable ht = new Hashtable();
            IQueryable<MessageInfo> messageInfo = _messageInfoService.GetList().Where(x=>x.StaffRecId==staff.Id&&x.IsDelete==0);
            if (!string.IsNullOrEmpty(SearchWord))
            {
                messageInfo = messageInfo.Where(x => x.Contents.Contains(SearchWord));
            }
            ht["code"] = 0;
            ht["count"]=messageInfo.Where(x=>x.IsRead==0).Count();
            ht["data"]= messageInfo.ToList();
            return Json(ht);
        }
        //保存历史消息
        [HttpPost]
        public JsonResult SaveChatMessage(string account, string message)
        {
            Hashtable ht = new Hashtable();
            string path = Server.MapPath($"/Assets/ChatMessage/{DateTime.Now.ToString("yyyyMMdd")}.txt");
            var chat = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {account}: {message}";
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter streamWriter = new StreamWriter(fs);
            streamWriter.WriteLine(chat);
            streamWriter.Close();
            fs.Close();
            ht["code"] = 0;
            return Json(ht);
        }
        //显示历史消息
        [HttpPost]
        public JsonResult ShowChatMessage()
        {
            Hashtable ht = new Hashtable();
            List<MessageVM> messageList = new List<MessageVM>();
            string path = Server.MapPath($"/Assets/ChatMessage/{DateTime.Now.ToString("yyyyMMdd")}.txt");
            // 使用正则表达式解析(txt文档中保存的信息的格式为[2025-1-1 12:30:30]admin:你好)
            string pattern = @"^\[(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\] (.+?): (.+)$";
            FileStream fs = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            while (true)
            {
                string line = sr.ReadLine();
                if (line == null)
                    break;
                Match match = Regex.Match(line, pattern);
                if (match.Success && match.Groups.Count >= 5)
                {
                    MessageVM messageItem = new MessageVM
                    {
                        Time = match.Groups[2].Value,       
                        Account = match.Groups[3].Value,   
                        Content = match.Groups[4].Value     
                    };
                    messageList.Add(messageItem);
                }
            }
            sr.Close();
            fs.Close();
            ht["code"] = 0;
            ht["data"] = messageList;
            return Json(ht);
        }
        //标记为已读
        [HttpPost]
        public JsonResult MarkAsRead(string productData)
        {
            productData = HttpUtility.UrlDecode(productData);
            List<int> mailIds = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(productData);
            Hashtable ht = new Hashtable();
            Staff currentUser = HttpContext.Session["user"] as Staff;
            if (currentUser == null)
            {
                ht["code"] = 1;
                ht["msg"] = "用户未登录";
                return Json(ht);
            }
            IQueryable<MessageInfo> query = _messageInfoService.GetList().Where(x => x.StaffRecId == currentUser.Id && mailIds.Contains(x.Id));
            List<MessageInfo> mails = query.ToList();
            foreach(var mail in mails)
            {
                mail.IsRead = 1;
                _messageInfoService.Update(mail);
            }
            ht["code"] = 0;
            return Json(ht);
        }
        //逻辑删除邮件
        [HttpPost]
        public JsonResult DeleteMails(string productData)
        {
            productData = HttpUtility.UrlDecode(productData);
            List<int> mailIds = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(productData);
            Hashtable ht = new Hashtable();
            List<MessageInfo> mails = _messageInfoService.GetList().Where(m => mailIds.Contains(m.Id)).ToList();
            foreach (var mail in mails)
            {
                mail.IsDelete = 1;
                _messageInfoService.Update(mail);
            }
            ht["code"] = 0;
            return Json(ht);
        }
        #endregion
    }
}